import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import '../../utils/URLOpenUtils.dart';
import '../common/common_dialog.dart';
import 'controller/train_details_controller.dart';
import 'controller/train_history_controller.dart';
import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/14.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainTeacherCourseItemWidget2 extends StatefulWidget {
  final CourseAndTeacherBean cubean;
  final int index;

  final isScaffold;

  const TrainTeacherCourseItemWidget2(
      {Key key, this.cubean, this.index, this.isScaffold = true})
      : super(key: key);

  @override
  _TrainTeacherCourseItemWidget2State createState() =>
      _TrainTeacherCourseItemWidget2State();
}

class _TrainTeacherCourseItemWidget2State
    extends State<TrainTeacherCourseItemWidget2>
    with SingleTickerProviderStateMixin, TrainModel {
  @override
  void initState() {
    super.initState();
  }

  List<CourseBean> _list = [];

  @override
  Widget build(BuildContext context) {
    String userName = "无教师";
    if (widget.cubean.userEntity != null) {
      userName = widget.cubean.userEntity.reamName;
    }
    //课程状态  0 未上课  1 正在上课中  2上课完成
    int courseStatues = widget.cubean.courseStatues;

    int userCourseStatues = widget.cubean.userCourseStatues;

    Color textColor = Color(0xff555555);
    if (courseStatues == 1) {
      textColor = Colors.green;
    } else if (courseStatues == 2) {
      textColor = Colors.blue;
    }
    Color textColor2 = Color(0xff555555);
    if (userCourseStatues == 1) {
      textColor2 = Colors.green;
    }
    return Container(
      margin: EdgeInsets.only(top: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(right: 6, left: 6),
            margin: EdgeInsets.only(top: 3),
            child: Text("${widget.cubean.index}"),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    Expanded(
                        child: Text(
                      "教师 $userName",
                      style: TextStyle(fontWeight: FontWeight.bold),
                    )),
                    SizedBox(
                      width: 10,
                    ),
                    Text("${widget.cubean.teacherPeriod}课时"),
                  ],
                  crossAxisAlignment: CrossAxisAlignment.start,
                ),
                SizedBox(
                  height: 10,
                ),
                Row(
                  children: [
                    Expanded(
                        child: Row(
                      children: [
                        Text(
                          "课程状态：",
                          style: TextStyle(fontWeight: FontWeight.w500),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "${widget.cubean.courseStatuesStr}",
                          style: TextStyle(color: textColor),
                        ),
                      ],
                    )),
                    Expanded(
                        child: Row(
                      children: [
                        Text(
                          "是否上课：",
                          style: TextStyle(fontWeight: FontWeight.w500),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "${widget.cubean.userCourseStatuesStr}",
                          style: TextStyle(color: textColor2),
                        ),
                      ],
                    )),
                  ],
                  crossAxisAlignment: CrossAxisAlignment.start,
                ),
                Container(
                  color: Colors.grey[200],
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 8),
                  padding: EdgeInsets.all(4),
                  child: Wrap(
                    crossAxisAlignment: WrapCrossAlignment.start,
                    children: [
                      Text(
                        "培训内容:",
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      Text(
                        "${widget.cubean.teacherContent ?? "--"}",
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                        ),
                      ),
                    ],
                  ),
                ),
                buildStartTimeWidget(),
                buildTeacherSginWidget(),
                buildSignFocesWidget(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  buildStartTimeWidget() {
    if (widget.cubean.teacherContent == null) {
      return SizedBox();
    }
    return Container(
      color: Colors.grey[200],
      padding: EdgeInsets.all(8),
      margin: EdgeInsets.only(top: 1),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "培训时间:",
          ),
          Row(
            children: [
              Text(
                "${widget.cubean.beginTime} ~ ",
                style: TextStyle(fontSize: 12, color: Color(0xff666666)),
              ),
              Text(
                "${widget.cubean.endTime} ",
                style: TextStyle(fontSize: 12, color: Color(0xff666666)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  buildUserSginToTimeWidget() {
    if (widget.cubean.userSignStartTime == null) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "签到时间： ",
            style: TextStyle(fontSize: 14),
          ),
          Text(
            "${widget.cubean.userSignStartTime} ",
            style: TextStyle(fontSize: 14),
          ),
        ],
      ),
    );
  }

  buildTeacherSginUpTimeWidget() {
    if (!widget.cubean.showTeacherTime ||
        widget.cubean.teacherSignEndTime == null) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 4),
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "结束上课时间： ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Text(
            "${widget.cubean.teacherSignEndTime} ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
        ],
      ),
    );
  }

  buildTeacherSginWidget() {
    if (!widget.cubean.showTeacherTime ||
        widget.cubean.teacherSignStartTime == null) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 10),
      color: Colors.grey[200],
      padding: EdgeInsets.all(3),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text("教师开始上课信息"),
            ],
          ),
          buildTeacherSginToTimeWidget(),
          buildTeacherSginUpTimeWidget(),
        ],
      ),
    );
  }

  buildUserDistanceWidget() {
    if (widget.cubean.signLocationDistance == null) {
      return SizedBox();
    }
    return Container(
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "当前距离教师上课： ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Text(
            "${widget.cubean.signLocationDistance} 米 ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          SizedBox(width: 20),
          GestureDetector(
            onTap: () {
              double teacherLongitude = widget.cubean.teacherLongitude;
              double teacherLlatitude = widget.cubean.teacherLlatitude;
              String teacherAddress = widget.cubean.teacherAddress;
              URLOpenUtils.openAmap(teacherLongitude, teacherLlatitude,
                  address: teacherAddress, title: "培训地点");
            },
            child: Text(
              "导航",
              style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue),
            ),
          )
        ],
      ),
    );
  }

  buildTeacherSginToTimeWidget() {
    return Container(
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "开始上课时间： ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Text(
            "${widget.cubean.teacherSignStartTime} ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
        ],
      ),
    );
  }

  buildUserSginUpTimeWidget() {
    if (widget.cubean.userSignEndTime == null) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "签退时间： ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Text(
            "${widget.cubean.userSignEndTime} ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
        ],
      ),
    );
  }

  buildSignFocesWidget() {
    bool showUserStartSignTips = widget.cubean.showUserStartSignTips;
    return Container(
      color: Colors.grey[100],
      padding: EdgeInsets.all(8),
      margin: EdgeInsets.only(top: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  "签到要求:",
                ),
              ),
              buildSignToButton(),
            ],
          ),
          buildUserSginToTimeWidget(),
          buildSignToLocationTipsWidget(),
          buildSignToTips1Widget(),
          buildSingToTipsWidget(),
          Divider(),
          Row(
            children: [
              Expanded(
                child: Text(
                  "签退要求:",
                ),
              ),
              buildSignUpButton(),
            ],
          ),
          buildUserSginUpTimeWidget(),
          buildSignUpLocationTipsWidget(),
          buildSignUpTips1Widget(),
          buildSingUpTipsWidget(),
        ],
      ),
    );
  }

  buildSignToTips1Widget() {
    bool showUserStartSignTips = widget.cubean.showUserStartSignTips;
    if (!showUserStartSignTips) {
      return SizedBox();
    }
    String showUserStartSignTips1 = widget.cubean.showUserStartSignTips1;
    if (showUserStartSignTips1.isEmpty) {
      return SizedBox();
    }
    return Wrap(
      children: [
        Text(
          showUserStartSignTips1,
          style: TextStyle(fontSize: 14, color: Color(0xff666666)),
        ),
      ],
    );
  }

  buildSignUpTips1Widget() {
    bool showUserEndSignTips = widget.cubean.showUserEndSignTips;
    if (!showUserEndSignTips) {
      return SizedBox();
    }
    String showUserEndSignTips1 = widget.cubean.showUserEndSignTips1;
    if (showUserEndSignTips1.isEmpty) {
      return SizedBox();
    }
    return Wrap(
      children: [
        Text(
          showUserEndSignTips1,
          style: TextStyle(fontSize: 14, color: Color(0xff666666)),
        ),
      ],
    );
  }

  ///位置要求提示
  buildSignToLocationTipsWidget() {
    bool showUserStartSignTips = widget.cubean.showUserStartSignTips;
    if (!showUserStartSignTips) {
      return SizedBox();
    }
    String showUserStartSignTips3 = widget.cubean.showUserStartSignTips3;
    if (showUserStartSignTips3.isEmpty) {
      return SizedBox();
    }
    return Wrap(
      children: [
        Text(
          "${widget.cubean.isForceLocation ? "要求使用位置验证 签到位置距离不得超出 ${widget.cubean.forceLocation}m " : ""}  ",
          style: TextStyle(fontSize: 14, color: Color(0xff666666)),
        ),
        buildUserDistanceWidget(),
      ],
    );
  }

  buildSignUpLocationTipsWidget() {
    bool showUserStartSignTips = widget.cubean.showUserStartSignTips;
    if (!showUserStartSignTips) {
      return SizedBox();
    }
    String showUserEndSignTips3 = widget.cubean.showUserEndSignTips3;
    if (showUserEndSignTips3.isEmpty) {
      return SizedBox();
    }
    return Wrap(
      children: [
        Text(
          "${widget.cubean.isForceLocation ? "要求使用位置验证 签到位置距离不得超出 ${widget.cubean.forceLocation}m " : ""}  ",
          style: TextStyle(fontSize: 14, color: Color(0xff666666)),
        ),
        buildUserDistanceWidget(),
      ],
    );
  }

  buildSingToTipsWidget() {
    bool showUserCodeSign = widget.cubean.showUserCodeSign;
    if (!showUserCodeSign) {
      return SizedBox();
    }
    return GestureDetector(
      onTap: () {
        courseCodeSignRueqest();
      },
      child: Text(
        "签到位置出现误差时，可以向教师索要签到码，点击此处使用签到码签到",
        style: TextStyle(fontSize: 14, color: Colors.blue),
      ),
    );
  }

  buildSingUpTipsWidget() {
    bool showUserEndSign = widget.cubean.showUserCodeEndSign;
    if (!showUserEndSign) {
      return SizedBox();
    }
    return GestureDetector(
      onTap: () {
        courseCodeSignUpRueqest();
      },
      child: Text(
        "签退位置出现误差时，可以向教师索要签退码，点击此处使用签退码签退",
        style: TextStyle(fontSize: 14, color: Colors.blue),
      ),
    );
  }

  buildTeacherStartButton() {
    bool showTeacherStartSign = widget.cubean.showTeacherStartSign;
    if (showTeacherStartSign) {
      return ElevatedButton(
          onPressed: () {
            showStartCourseTips();
          },
          child: _signLoading ? LoadingWidget() : Text("开始上课"));
    }
    bool showTeacherEndSign = widget.cubean.showTeacherEndSign;
    if (showTeacherEndSign) {
      return ElevatedButton(
          onPressed: () {
            showEndCourseTips();
          },
          child: _signLoading ? LoadingWidget() : Text("结束上课"));
    }
    return SizedBox();
  }

  buildSignToButton() {
    /// APP 显示用户的签到按钮
    bool showUserStartSign = widget.cubean.showUserStartSign;
    if (showUserStartSign) {
      return ElevatedButton(
          onPressed: () {
            signRequest();
          },
          child: _signLoading ? LoadingWidget() : Text("签到"));
    }
    String showUserStartSignStr = widget.cubean.showUserStartSignStr;
    return Text(showUserStartSignStr);
  }

  buildSignUpButton() {
    /// APP 显示用户的签退按钮

    bool showUserEndSign = widget.cubean.showUserEndSign;
    if (showUserEndSign) {
      return ElevatedButton(
          onPressed: () {
            signUpCheckFunction();
          },
          child: _signUpLoading ? LoadingWidget() : Text("签退"));
    }

    String showUserEndSignStr = widget.cubean.showUserEndSignStr;

    return Text(showUserEndSignStr);
  }

  TextEditingController _textEditingController = new TextEditingController();

  void courseCodeSignRueqest() async {
    _textEditingController.clear();
    dynamic reault = await Get.defaultDialog(
      radius: 4,
      title: "温馨提示",
      content: Container(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 10,
            ),
            TextField(
              controller: _textEditingController,
              maxLength: 6,
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp("[0-9]")), //数字包括小数
              ],
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                  hintText: "请输入签到码", border: OutlineInputBorder()),
            )
          ],
        ),
      ),
      confirm: Container(
        alignment: Alignment.center,
        child: TextButton(
          onPressed: () {
            String result = _textEditingController.text;
            if (result.length == 0) {
              ToastUtils.showToast("请输入签到码");
              return;
            }
            Get.back(result: true);
          },
          child: Text(
            "确认",
            style: TextStyle(color: Colors.blue),
          ),
        ),
        width: 100,
      ),
      cancel: Container(
        alignment: Alignment.center,
        child: TextButton(
            onPressed: () {
              Get.back(result: false);
            },
            child: Text("取消")),
        width: 100,
      ),
    );

    if (reault == null || !reault) {
      _textEditingController.clear();
      return;
    }
    signRequest();
  }

  TextEditingController _textEditingController2 = new TextEditingController();

  void courseCodeSignUpRueqest() async {
    _textEditingController2.clear();
    dynamic reault = await Get.defaultDialog(
      radius: 4,
      title: "温馨提示",
      content: Container(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 10,
            ),
            TextField(
              controller: _textEditingController2,
              maxLength: 6,
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp("[0-9]")), //数字包括小数
              ],
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                  hintText: "请输入签退码", border: OutlineInputBorder()),
            )
          ],
        ),
      ),
      confirm: Container(
        alignment: Alignment.center,
        child: TextButton(
          onPressed: () {
            String result = _textEditingController2.text;
            if (result.length == 0) {
              ToastUtils.showToast("请输入签退码");
              return;
            }
            Get.back(result: true);
          },
          child: Text(
            "确认",
            style: TextStyle(color: Colors.blue),
          ),
        ),
        width: 100,
      ),
      cancel: Container(
        alignment: Alignment.center,
        child: TextButton(
            onPressed: () {
              Get.back(result: false);
            },
            child: Text("取消")),
        width: 100,
      ),
    );

    if (reault == null || !reault) {
      _textEditingController2.clear();
      return;
    }
    signUpRequest();
  }

  bool _signLoading = false;
  bool _signUpLoading = false;

  ///签到
  void signRequest() async {
    setState(() {
      _signLoading = true;
    });
    String courseCode = _textEditingController.text.trim();
    TrainCourseSignBean trainCourseSignBean =
        await trainCourseSign(widget.cubean, courseCode: courseCode);

    if (trainCourseSignBean != null) {
      ToastUtils.showToast("签到成功");
      widget.cubean.userSignStartTime = trainCourseSignBean.signToTime;
      widget.cubean.showUserStartSign = false;
      if (Get.isRegistered<TrainDetailsController>()) {
        Get.find<TrainDetailsController>().update();
      }
      if (Get.isRegistered<TrainHistoryController>(tag: "main")) {
        Get.find<TrainHistoryController>(tag: "main").requestListFunction();
      }
    }
    setState(() {
      _signLoading = false;
    });
  }

  ///签退
  void signUpCheckFunction() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定签退吗??",
        selectCallBack: () {
          signUpRequest();
        });
  }

  ///签退
  void signUpRequest() async {
    setState(() {
      _signUpLoading = true;
    });
    String courseCode = _textEditingController2.text.trim();
    TrainCourseSignBean trainCourseSignBean =
        await trainCourseSignUp(widget.cubean, courseCode: courseCode);
    if (trainCourseSignBean != null) {
      ToastUtils.showToast("签退成功");
      widget.cubean.userSignEndTime = trainCourseSignBean.signUpTime;
      widget.cubean.showUserEndSign = false;
      if (Get.isRegistered<TrainDetailsController>()) {
        Get.find<TrainDetailsController>().update();
      }
      if (Get.isRegistered<TrainHistoryController>(tag: "main")) {
        Get.find<TrainHistoryController>(tag: "main").requestListFunction();
      }
    }
    setState(() {
      _signUpLoading = false;
    });
  }

  ///-----------------------教师 start -----------------------------------------------------------------------
  ///开始上课
  showStartCourseTips() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定开始上课吗??",
        selectCallBack: () {
          teacherSignRequest();
        });
  }

  void teacherSignRequest() async {
    setState(() {
      _signLoading = true;
    });
    TrainCourseSignBean trainCourseSignBean =
        await trainTeacherCourseSign(widget.cubean);
    if (trainCourseSignBean != null) {
      ToastUtils.showToast("操作成功");
      widget.cubean.teacherSignStartTime = trainCourseSignBean.signToTime;
      widget.cubean.signRecoderId = trainCourseSignBean.id;
      widget.cubean.showTeacherStartSign = false;
      widget.cubean.showTeacherEndSign = true;
      if (Get.isRegistered<TrainDetailsController>()) {
        Get.find<TrainDetailsController>().update();
      }
    }
    setState(() {
      _signLoading = false;
    });
  }

  showEndCourseTips() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定结束上课吗??",
        selectCallBack: () {
          teacherSignUpRequest();
        });
  }

  void teacherSignUpRequest() async {
    setState(() {
      _signLoading = true;
    });
    TrainCourseSignBean trainCourseSignBean =
        await trainTeacherCourseSignUp(widget.cubean);
    if (trainCourseSignBean != null) {
      ToastUtils.showToast("操作成功");
      widget.cubean.teacherSignEndTime = trainCourseSignBean.signUpTime;
      widget.cubean.showTeacherStartSign = false;
      widget.cubean.showTeacherEndSign = false;
      if (Get.isRegistered<TrainDetailsController>()) {
        Get.find<TrainDetailsController>().update();
      }
    }
    setState(() {
      _signLoading = false;
    });
  }
}
